﻿using UnityEngine;
//using UnityEditor;
using System.Collections;

public class GridBehaviourScript : MonoBehaviour {

	public GameObject cardPrefab;
	// ATTENTION : Only even number
	public int size;
	public GUIText scoreText;
	public GUITexture bravoText;
	public string assetsPath;

	//private Material[] materials;
	private Object[] materials; // Liste de toutes les textures du répertoire
	private int nbMaterials;
	private GameObject[] cards;
	private int[] indexes;
	private int[] materialIndexes;
	private bool rotating = false;
	private int nbCardTurned = 0;
	private Transform[] turnedCards = new Transform[2];
	private bool beingHandled = false;
	private int score = 0;

	void Start () {
		//materials = Resources.LoadAll<Material>(assetsPath);
		materials = Resources.LoadAll ("Textures/Common/Letters");
		if (materials == null || materials.Length == 0) {
			Debug.LogError("No materials found");
			return;
		}
		nbMaterials = materials.Length;

		bravoText.enabled = false;

		if (size % 2 != 0) {
			Debug.LogError("Size must be an even number");
			return;
		}
		
		int totalSize = size * size;
		int range = (totalSize / 2);

		if (materials.Length < range) {
			Debug.LogError("Materiels length ("+materials.Length+") must be >= "+range);
			return;
		}

		indexes = new int[totalSize];
		cards = new GameObject[totalSize];

		ArrayList freeIndexes = new ArrayList ();
		for (int i = 0; i < nbMaterials; i++) {
			freeIndexes.Add (i);
		}

		materialIndexes = new int[totalSize];
		for (int i = 0; i < totalSize; i++) {
			int currentIndex = Random.Range(0, nbMaterials);
			while (! freeIndexes.Contains(currentIndex)) {
				currentIndex = Random.Range(0, nbMaterials);
			}
			freeIndexes.Remove(currentIndex);
			materialIndexes[i] = currentIndex;
		}

		Vector2 cardSize = cardPrefab.transform.FindChild ("Front").GetComponent<Renderer>().bounds.size;
		float centerSpaceSize = 2f;
		float cardSpaceSize = centerSpaceSize - cardSize.x;

		float offset = ((size / 2f) - 1) * (cardSize.x + cardSpaceSize) + (cardSpaceSize / 2) + (cardSize.x / 2f);
		Vector3 origin = new Vector3 (-offset, -offset, 0);

		Random.seed = (int)System.DateTime.Now.Ticks;

		for (int y = 0; y < size; y++) {
			for (int x = 0; x < size; x++) {
				int pos = y * size + x;
				cards [pos] = Instantiate (cardPrefab, new Vector3 (0, 0, 0), Quaternion.identity) as GameObject;
				cards [pos].name = "Card" + x + "x" + y;
				cards [pos].transform.position = new Vector3(origin.x + (x * 2f), origin.y + (y * 2f), 0);
				cards [pos].transform.parent = this.transform;

				int index = Random.Range(0, range);

				while (indexes[index] == 2) {
					index = Random.Range(0, range);
				}

				indexes[index]++;

				cards [pos].transform.FindChild("Back").GetComponent<Renderer>().material.mainTexture = materials[materialIndexes[index]] as Texture2D;
				// cards [pos].transform.FindChild("Back").GetComponent<Renderer>().material = materials[materialIndexes[index]];
			}
		}
	}
	
	void Update () {
		// If 2 cards are turned
		if (nbCardTurned == 2 && !beingHandled) {
			// If they are identical
			if (turnedCards[0].transform.FindChild("Back").GetComponent<Renderer>().material.mainTexture.name == turnedCards[1].transform.FindChild("Back").GetComponent<Renderer>().material.mainTexture.name) {
				nbCardTurned = 0;
				turnedCards[0] = null;
				turnedCards[1] = null;
				score++;
				scoreText.text = "Score : "+score;
				if (score == size * 2) {
					bravoText.enabled = true;
				}
			} else {
				StartCoroutine ( HandleUpdate() );
//				turnedCards[0].GetComponent<CardBehaviourScript> ().turnCard (this.gameObject);
//				turnedCards[1].GetComponent<CardBehaviourScript> ().turnCard (this.gameObject);
//				nbCardTurned = 0;
//				turnedCards[0] = null;
//				turnedCards[1] = null;
			}
		}
	}

	void OnDestroy() {
	}

	public void OnCardClick(Transform card) {
		//Debug.Log ("CLICKED " + card.name);
		if (! rotating && ! beingHandled) {
			turnedCards[nbCardTurned] = card;
			card.GetComponent<CardBehaviourScript> ().turnCard (this.gameObject);
			GetComponent<AudioSource>().Play();
		}
	}

	private IEnumerator HandleUpdate() {
		beingHandled = true;

		#if !UNITY_STANDALONE
		Handheld.Vibrate ();
		#endif
		iTween.ShakePosition (Camera.main.gameObject, new Vector3 (0.1f, 0.1f, 0.1f), 0.5f);

		yield return new WaitForSeconds ( 1.0f );
		beingHandled = false;

		turnedCards[0].GetComponent<CardBehaviourScript> ().turnCard (this.gameObject);
		turnedCards[1].GetComponent<CardBehaviourScript> ().turnCard (this.gameObject);
		nbCardTurned = 0;
		turnedCards[0] = null;
		turnedCards[1] = null;
	}

	public bool Rotating {
		set { this.rotating = value; }
		get { return this.rotating; }
	}

	public int NbCardTurned {
		set { this.nbCardTurned = value; }
		get { return this.nbCardTurned; }
	}

}
